package com.dc.mp.handler;

import com.dc.base.BaseResponse;
import com.dc.constant.Constants;
import com.dc.core.utils.RedisUtils;
import com.dc.core.utils.RegxUtils;
import com.dc.member.output.dto.UserOutputDTO;
import com.dc.mp.builder.TextBuilder;
import com.dc.weixin.feign.WeixinFeignMember;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;

/**
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
public class MsgHandler extends AbstractHandler {

    /**
     * 发送验证码消息
     */
    @Value("${dc.weixin.registration.code.message}")
    private String registrationCodeMessage;
    /**
     * 默认回复消息
     */
    @Value("${dc.weixin.default.registration.code.message}")
    private String defaultRegistrationCodeMessage;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private WeixinFeignMember weixinFeignMember; //微信调用会员数据库

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {
        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StringUtils.startsWithAny(wxMessage.getContent(), "你好", "客服")
                    && weixinService.getKefuService().kfOnlineList()
                    .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }

        //TODO 组装回复消息
        //String content = "收到信息内容：" + JsonUtils.toJson(wxMessage);
        String content = "你好，欢迎关注";
        //1、获取微信客户端发送的消息
        String fromContent = wxMessage.getContent();
        //2、使用正则表达式，验证消息是否为手机号码格式
        if (RegxUtils.checkMobile(fromContent)) {
            //根据手机号码，调用会员服务接口查询用户信息是否存在。
            BaseResponse<UserOutputDTO> resultUserInfo = weixinFeignMember.existMobile(fromContent);
            //判断手机号是否存在
            if (resultUserInfo.getRtnCode().equals(Constants.HTTP_RES_CODE_200)) {
                return new TextBuilder().build("该手机号" + fromContent + "已经存在", wxMessage, weixinService);
            }
            //解决注册参数不正确的问题，但是并不是手机号已经存在的别的错误
            if (!resultUserInfo.getRtnCode().equals(Constants.HTTP_RES_CODE_EXISTMOBILE_203)) {
                return new TextBuilder().build(resultUserInfo.getMsg(), wxMessage, weixinService);
            }
            //3、如果是手机号码格式，随机生成四位数字注册码
            int registCode = registCode();
            //4、key手机号 value 注册码 存放到redis中
            //加个前缀
            redisUtils.setString(Constants.WEIXINCODE_KEY + fromContent, registCode + "", Constants.WEIXINCODE_TIMEOUT);
            String returncode = String.format(registrationCodeMessage, registCode);
            return new TextBuilder().build(returncode, wxMessage, weixinService);
        }
        //做第三方机器人的接口，做人机回答，图灵机器人就可以了
        return new TextBuilder().build(defaultRegistrationCodeMessage, wxMessage, weixinService);
    }

    //获取注册码
    private int registCode() {
        int registCode = (int) (Math.random() * 9000 + 1000);
        return registCode;
    }

}
